package cn.xnatural.demo.ctrl;

import cn.xnatural.app.Bean;
import cn.xnatural.app.ServerTpl;
import cn.xnatural.demo.entity.User;
import cn.xnatural.jpa.Repo;
import cn.xnatural.xchain.Route;
import cn.xnatural.xnet.R;

import java.util.regex.Pattern;


@Bean
public class UserCtrl extends ServerTpl {

    protected Repo repo = bean(Repo.class);

    // 用户名限制: 字母和数字组成且只能字母开头
    protected final Pattern namePattern = Pattern.compile("^[a-zA-Z][\\w]+$");


    @Route(path = "register")
    public R<User> reg(String username, String password) {
        if (username == null || username.isEmpty() || !namePattern.matcher(username).find()) {
            return R.of("02", "用户名规则: 字母和数字组成且只能字母开头");
        }
        if (password == null || password.isEmpty()) {
            return R.of("02", "密码规则: 字母(大小写),数字,字符都包含");
        }

        User u = repo.byAttr(User.class, "name", username);
        if (u == null) {
            u = new User();
            u.setName(name);
            u.setPassword(password);
            repo.saveOrUpdate(u);
        } else {
            return R.of("02", "用户名已经存在");
        }
        return R.ok();
    }

    public R login() {
        return R.ok();
    }

}
